﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;
using Microsoft.SharePoint;

namespace SIMSProject.Views.Report.SaleReport
{
    public partial class SaleReportUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.LoadData();
            }
        }

        private void LoadData()
        {
            ListItemCollection items = new ListItemCollection();
            items.Add(new ListItem("", ""));
            items.Add(new ListItem("Product Sale Report", "Product Sale Report"));
            items.Add(new ListItem("Sale Analysis Report", "Sale Analysis Report"));
            items.Add(new ListItem("Compare Sale Analysis Report", "Compare Sale Analysis Report"));

            this.ddlReportType.DataSource = items;
            this.ddlReportType.DataBind();
        }

        protected void ddlReportType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.ddlReportType.SelectedValue))
            {
                switch (this.ddlReportType.SelectedValue)
                {
                    case "Product Sale Report":
                        this.compareSale.Visible = false;
                        this.productsale.Visible = true;
                        break;
                    case "Sale Analysis Report":
                        this.compareSale.Visible = false;
                        this.productsale.Visible = false;
                        this.LoadControlForSaleAnalysisReport();
                        break;
                    case "Compare Sale Analysis Report":
                        this.compareSale.Visible = true;
                        this.productsale.Visible = false;
                        break;
                    default: 
                        break;
                }
            }
        }

        private void LoadControlForSaleAnalysisReport()
        {
            Chart saleDataChart = new Chart();
            saleDataChart.ImageStorageMode = ImageStorageMode.UseImageLocation;

            saleDataChart.Legends.Add("Legend");
            saleDataChart.Width = 1000;
            saleDataChart.Height = 600;
            //saleDataChart.RenderType = RenderType.ImageTag;
            string imagePath = "~/_layouts/ChartImages/";

            saleDataChart.ImageLocation = imagePath + "ChartPic_#SEQ(200,30)";
            //saleDataChart.Palette = ChartColorPalette.Berry;

            ChartArea area = new ChartArea();
            area.BorderDashStyle = ChartDashStyle.Solid;
            area.BackSecondaryColor = Color.White;
            area.ShadowColor = Color.Transparent;
            area.BackGradientStyle = GradientStyle.TopBottom;
            area.AxisY.Title = "Revenue ($)";
            area.AxisX.Title = "Month";
            area.AxisX.Interval = 1;

            saleDataChart.ChartAreas.Add(area);
            // Create new data series and set it's visual attributes
            Series series = new Series("Total Revenue");
            series.ChartType = SeriesChartType.Spline;
            series.BorderWidth = 3;
            series.ShadowOffset = 2;

            for (int i = 1; i <= 12; i++)
            {
                DateTime firstDate = new DateTime(DateTime.Now.Year, i, 1);
                DateTime lastDate = firstDate.AddMonths(1).AddDays(-1);
                firstDate = new DateTime(DateTime.Now.Year, i, 1);

                SPQuery query = new SPQuery();
                query.Query = @"<Where>
                              <And>
                                  <And>
                                     <Geq>
                                        <FieldRef Name='Finished_x0020_Date' />
                                        <Value Type='DateTime'>" + firstDate.ToString("yyyy-MM-dd") + @"</Value>
                                     </Geq>
                                     <Leq>
                                        <FieldRef Name='Finished_x0020_Date' />
                                        <Value Type='DateTime'>" + lastDate.ToString("yyyy-MM-dd") + @"</Value>
                                     </Leq>
                                  </And>
                                       <Eq>
                                         <FieldRef Name='Status' />
                                         <Value Type='Choice'>Finished</Value>
                                      </Eq>
                               </And>
                           </Where>";

                SPListItemCollection orderItems = SPContext.Current.Web.Lists["Order"].GetItems(query);

                int total = this.CountTotalPrice(orderItems);
                series.Points.AddY(total);
            }

            saleDataChart.Series.Add(series);
            saleDataChart.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
            saleDataChart.BorderColor = Color.FromArgb(26, 59, 105);
            saleDataChart.BorderlineDashStyle = ChartDashStyle.Solid;
            saleDataChart.BorderWidth = 1;

            this.reportResult.Controls.Clear();
            this.reportResult.Controls.Add(saleDataChart);
        }

        private int CountTotalPrice(SPListItemCollection items)
        {
            int totalQuantity = 0;
            for (int i = 0; i < items.Count; i++)
            {
                int temp = 0;
                if (Int32.TryParse(Convert.ToString(items[i]["Total Price"]), out temp))
                {
                    totalQuantity += temp;
                }
            }

            return totalQuantity;
        }

        protected void btShowCompareSale_Click(object sender, EventArgs e)
        {
            int number = 0;
            int currentYear = DateTime.Now.Year;

            if (Int32.TryParse(this.tbNumberOfYear.Text, out number))
            {
                Chart chrtSalesData = new Chart();
                chrtSalesData.ImageStorageMode = ImageStorageMode.UseImageLocation;

                chrtSalesData.Legends.Add("Legend");
                chrtSalesData.Width = 1000;
                chrtSalesData.Height = 600;
                chrtSalesData.RenderType = RenderType.ImageTag;
                string imagePath = "~/_layouts/ChartImages/";

                chrtSalesData.ImageLocation = imagePath + "ChartPic_#SEQ(200,30)";
                chrtSalesData.Palette = ChartColorPalette.Berry;

                Title chartTitle = new Title("Compare Sale Revenue", Docking.Top, new Font("Calibri", 12, FontStyle.Bold), Color.FromArgb(26, 59, 105));
                chrtSalesData.Titles.Add(chartTitle);
                chrtSalesData.ChartAreas.Add("Inventory");

                for (int i = number; i >=0 ; i--)
                {
                    chrtSalesData.Series.Add((currentYear-i).ToString());

                    for (int j = 1; j <= 12; j++)
                    {
                        DateTime firstDate = new DateTime(currentYear-i, j, 1);
                        DateTime lastDate = firstDate.AddMonths(1).AddDays(-1);
                        firstDate = new DateTime(currentYear - i, j, 1);

                        SPQuery query = new SPQuery();
                        query.Query = @"<Where>
                              <And>
                                  <And>
                                     <Geq>
                                        <FieldRef Name='Finished_x0020_Date' />
                                        <Value Type='DateTime'>" + firstDate.ToString("yyyy-MM-dd") + @"</Value>
                                     </Geq>
                                     <Leq>
                                        <FieldRef Name='Finished_x0020_Date' />
                                        <Value Type='DateTime'>" + lastDate.ToString("yyyy-MM-dd") + @"</Value>
                                     </Leq>
                                  </And>
                                       <Eq>
                                         <FieldRef Name='Status' />
                                         <Value Type='Choice'>Finished</Value>
                                      </Eq>
                               </And>
                           </Where>";

                        SPListItemCollection orderItems = SPContext.Current.Web.Lists["Order"].GetItems(query);

                        int total = this.CountTotalPrice(orderItems);
                        chrtSalesData.Series[(currentYear - i).ToString()].Points.AddY(total);
                    }
                }

                chrtSalesData.ChartAreas[0].AxisX.Interval = 1;
                chrtSalesData.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
                chrtSalesData.BorderColor = Color.FromArgb(26, 59, 105);
                chrtSalesData.BorderlineDashStyle = ChartDashStyle.Solid;
                chrtSalesData.BorderWidth = 1;

                this.reportResult.Controls.Clear();
                this.reportResult.Controls.Add(chrtSalesData);
            }
        }

        protected void btShowProductSaleReport_Click(object sender, EventArgs e)
        {
            if (this.fromDate.SelectedDate > this.toDate.SelectedDate)
            {
                this.lblValidateText.Visible = true;
                this.lblValidateText.Text = "The to date must greater than from date";
                return;
            }
            else
            {
                this.lblValidateText.Visible = false;
            }

            Chart chrtSalesData = new Chart();
            chrtSalesData.ImageStorageMode = ImageStorageMode.UseImageLocation;

            chrtSalesData.Legends.Add("Legend");
            chrtSalesData.Width = 1000;
            chrtSalesData.Height = 600;
            chrtSalesData.RenderType = RenderType.ImageTag;
            string imagePath = "~/_layouts/ChartImages/";

            chrtSalesData.ImageLocation = imagePath + "ChartPic_#SEQ(200,30)";
            chrtSalesData.Palette = ChartColorPalette.Berry;

            Title chartTitle = new Title("Sale Product Report", Docking.Top, new Font("Calibri", 12, FontStyle.Bold), Color.FromArgb(26, 59, 105));
            chrtSalesData.Titles.Add(chartTitle);
            chrtSalesData.ChartAreas.Add("Inventory");

            chrtSalesData.Series.Add(new Series("Chart Sale"));
            chrtSalesData.Series[0].ChartType = SeriesChartType.Pie;
            chrtSalesData.Series[0]["PieLabelStyle"] = "Inside";
            chrtSalesData.ChartAreas[0].Area3DStyle.Enable3D = true;

            // Add Data to Display
            string[] xValues = { "A", "B", "C", "D" };
            int[] yValues = { 20, 30, 50, 40 };
            chrtSalesData.Series[0].Points.DataBindXY(xValues, yValues);

            // Call Out The Letter "D"
            chrtSalesData.Series[0].Points[3]["Exploded"] = "true";
            chrtSalesData.Series[0].LabelToolTip = "#PERCENT";

            chrtSalesData.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
            chrtSalesData.BorderColor = Color.FromArgb(26, 59, 105);
            chrtSalesData.BorderlineDashStyle = ChartDashStyle.Solid;
            chrtSalesData.BorderWidth = 1;

            this.reportResult.Controls.Clear();
            this.reportResult.Controls.Add(chrtSalesData);
        }
    }
}
